package cn.wolfcode.mq;

import cn.wolfcode.websocket.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName OrderResultMQConsumer
 * @Author VCR
 * @Date 2022/1/2 16:22
 * @Version 1.0
 */

@Component
@Slf4j
@RocketMQMessageListener(topic = MQConstant.ORDER_RESULT_TOPIC,consumerGroup = "OrderResultMQConsumer")
public class OrderResultMQConsumer implements RocketMQListener<OrderMQResult> {

    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("消费者进入通知队列");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String token = orderMQResult.getToken();    // 获取token
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);   // 根据token找到客户端信息
        if (webSocketServer != null) {
            try {
                // 拿到客户端会话信息 给客户端去发送数据
                webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
